package com.healthybear.demo.languagechange

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.fragment.app.Fragment

/**
 * LanguageFragment provides language selection interface
 * 
 * Requirements addressed:
 * - 7.1: RadioGroup with three RadioButtons for supported languages
 * - 7.2: Configure switching behavior based on implementation type
 * - 7.3: Show loading dialog during language switching process
 * - 7.4: Implement activity restart for methods that require it
 */
class LanguageFragment : Fragment() {
    
    private lateinit var implementationType: LanguageUtils.ImplementationType
    private lateinit var radioGroup: RadioGroup
    private lateinit var englishRadio: RadioButton
    private lateinit var chineseRadio: RadioButton
    private lateinit var japaneseRadio: RadioButton
    private var loadingDialogManager: LoadingDialogManager? = null
    
    companion object {
        private const val ARG_IMPLEMENTATION_TYPE = "implementation_type"
        
        /**
         * Factory method to create LanguageFragment with specific implementation type
         */
        fun newInstance(implementationType: LanguageUtils.ImplementationType): LanguageFragment {
            return LanguageFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_IMPLEMENTATION_TYPE, implementationType.name)
                }
            }
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // Get implementation type from arguments
        val implementationTypeName = arguments?.getString(ARG_IMPLEMENTATION_TYPE)
        implementationType = if (implementationTypeName != null) {
            LanguageUtils.ImplementationType.valueOf(implementationTypeName)
        } else {
            LanguageUtils.ImplementationType.CONFIGURATION_UPDATE // Default
        }
    }
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_language, container, false)
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // Initialize loading dialog manager
        loadingDialogManager = LoadingDialogManager(requireContext())
        
        setupLanguageSelection(view)
        updateCurrentSelection()
    }
    
    /**
     * Set the implementation type for language switching behavior
     * Requirement 7.2: Configure switching behavior based on implementation type
     */
    fun setImplementationType(type: LanguageUtils.ImplementationType) {
        implementationType = type
    }
    

    
    /**
     * Set up the language selection interface
     * Requirement 7.1: RadioGroup with three RadioButtons for supported languages
     */
    private fun setupLanguageSelection(view: View) {
        radioGroup = view.findViewById(R.id.languageRadioGroup)
        englishRadio = view.findViewById(R.id.englishRadio)
        chineseRadio = view.findViewById(R.id.chineseRadio)
        japaneseRadio = view.findViewById(R.id.japaneseRadio)
        
        // Set up radio button texts with proper localization
        englishRadio.text = getString(R.string.language_english)
        chineseRadio.text = getString(R.string.language_chinese)
        japaneseRadio.text = getString(R.string.language_japanese)
        
        // Set up selection listener
        radioGroup.setOnCheckedChangeListener { _, checkedId ->
            val selectedLanguage = when (checkedId) {
                R.id.englishRadio -> LanguageUtils.SupportedLanguage.ENGLISH.code
                R.id.chineseRadio -> LanguageUtils.SupportedLanguage.CHINESE.code
                R.id.japaneseRadio -> LanguageUtils.SupportedLanguage.JAPANESE.code
                else -> return@setOnCheckedChangeListener
            }
            
            onLanguageSelected(selectedLanguage)
        }
    }
    
    /**
     * Update the current selection based on saved preference
     */
    private fun updateCurrentSelection() {
        val currentLanguage = LanguageUtils.getLanguagePreference(requireContext())
        
        val radioButtonId = when (currentLanguage) {
            LanguageUtils.SupportedLanguage.ENGLISH.code -> R.id.englishRadio
            LanguageUtils.SupportedLanguage.CHINESE.code -> R.id.chineseRadio
            LanguageUtils.SupportedLanguage.JAPANESE.code -> R.id.japaneseRadio
            else -> R.id.englishRadio // Default to English
        }
        
        radioGroup.check(radioButtonId)
    }
    
    /**
     * Handle language selection
     * Requirements 1.3, 1.4, 7.1, 7.2, 7.3, 7.4: Language selection logic
     */
    private fun onLanguageSelected(languageCode: String) {
        try {
            val currentLanguage = LanguageUtils.getLanguagePreference(requireContext())
            
            // Don't do anything if the same language is selected
            if (currentLanguage == languageCode) {
                return
            }
            
            // Requirement 7.2: Prevent additional language change requests during loading
            if (loadingDialogManager?.isLoadingDialogShowing() == true) {
                android.util.Log.w("LanguageFragment", "Language change already in progress, ignoring request")
                return
            }
            
            // Validate language code before proceeding
            val validationResult = ErrorHandler.validateLanguageCode(languageCode)
            if (validationResult is ErrorHandler.ValidationResult.Invalid) {
                ErrorHandler.handleLanguageSwitchError(
                    requireContext(),
                    IllegalArgumentException(validationResult.reason),
                    ErrorHandler.ErrorType.UNSUPPORTED_LANGUAGE
                )
                updateCurrentSelection() // Revert to previous selection
                return
            }
            
            // Show loading dialog with timeout handling
            showLoadingDialog()
            
            // Apply language change based on implementation type with error handling
            val success = try {
                when (implementationType) {
                    LanguageUtils.ImplementationType.APP_COMPAT_DELEGATE -> {
                        LanguageUtils.setLanguageMethod1(requireContext(), languageCode)
                    }
                    LanguageUtils.ImplementationType.CONFIGURATION_UPDATE -> {
                        LanguageUtils.setLanguageMethod2(requireContext(), languageCode)
                    }
                    LanguageUtils.ImplementationType.SYSTEM_SETTINGS -> {
                        LanguageUtils.openSystemLanguageSettings(requireContext())
                    }
                }
            } catch (e: Exception) {
                ErrorHandler.handleLanguageSwitchError(
                    requireContext(),
                    e,
                    ErrorHandler.ErrorType.UNKNOWN_ERROR
                )
                false
            }
            
            if (success) {
                // For methods that require restart, restart the activity
                if (implementationType == LanguageUtils.ImplementationType.CONFIGURATION_UPDATE) {
                    // Requirement 7.4: Implement activity restart for methods that require it
                    activity?.let { activity ->
                        if (activity is BaseActivity) {
                            // Use a slight delay to ensure the loading dialog is visible
                            view?.postDelayed({
                                dismissLoadingDialog()
                                activity.restartActivity()
                            }, 500)
                        }
                    }
                } else {
                    // For other methods, just dismiss the loading dialog
                    view?.postDelayed({
                        dismissLoadingDialog()
                    }, 1000)
                }
            } else {
                // Handle error case - dismiss loading and revert selection
                handleLanguageChangeError(languageCode)
            }
            
        } catch (e: Exception) {
            // Catch any unexpected errors
            ErrorHandler.handleLanguageSwitchError(
                requireContext(),
                e,
                ErrorHandler.ErrorType.UNKNOWN_ERROR
            )
            handleLanguageChangeError(languageCode)
        }
    }
    
    /**
     * Handle language change errors by dismissing loading dialog and reverting selection
     */
    private fun handleLanguageChangeError(attemptedLanguageCode: String) {
        dismissLoadingDialog()
        
        // Log the error context
        ErrorHandler.logErrorWithContext(
            "LanguageFragment",
            "Language change failed, reverting selection",
            context = mapOf(
                "attemptedLanguage" to attemptedLanguageCode,
                "implementationType" to implementationType.name
            )
        )
        
        // Revert selection to previous language
        updateCurrentSelection()
    }
    
    /**
     * Show loading dialog during language switching
     * Requirement 7.1, 7.3: Show loading dialog during language switching process with timeout
     */
    private fun showLoadingDialog() {
        loadingDialogManager?.showLoadingDialog(
            message = getString(R.string.loading_language_change),
            timeoutMs = 5000L,
            onTimeout = {
                android.util.Log.w("LanguageFragment", "Loading dialog timeout reached")
                // Revert selection to previous language on timeout
                updateCurrentSelection()
            }
        )
    }
    
    /**
     * Dismiss the loading dialog
     * Requirement 7.3: Dismiss loading dialog when operation completes
     */
    private fun dismissLoadingDialog() {
        loadingDialogManager?.dismissLoadingDialog()
    }
    
    override fun onDestroyView() {
        // Clean up loading dialog manager
        loadingDialogManager?.cleanup()
        loadingDialogManager = null
        super.onDestroyView()
    }
}